package com.miukoo.aikao.admin.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.miukoo.aikao.admin.service.JwtUserRedisService;
import com.miukoo.aikao.core.pojos.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 用户缓存登录用户信息
 * @Author miukoo<miukoo@126.com>
 * @Date 2020/11/20  
 * @Version 1.0
 */
@Service
public class JwtUserRedisServiceImpl extends RedisServiceImpl implements JwtUserRedisService {

    // 时间间隔超过5分钟，则重新刷新用户的登录有效时长
    private final static Long UPDATE_TIME_STEP = 300_000L;

    private final static Long SESSION_TIME = new Long(30 * 60);
    private final static String USER_PREFIX = "SECURITY_USER_";
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public String saveUser(SecurityUser user) throws JsonProcessingException {
        user.setLastTime(System.currentTimeMillis());
        String jwtId = UUID.randomUUID().toString();
        user.setJti(jwtId);
        String json = objectMapper.writeValueAsString(user);
        set(USER_PREFIX+jwtId,json,SESSION_TIME);
        return jwtId;
    }

    @Override
    public SecurityUser getUser(String jwtId) throws JsonProcessingException {
        SecurityUser user =  getJson(USER_PREFIX+jwtId,SecurityUser.class);
        if(user!=null){
            Long temp = System.currentTimeMillis()-user.getLastTime();
            if(temp>UPDATE_TIME_STEP){
                System.out.println("===============刷新token");
                user.setLastTime(System.currentTimeMillis());
                String json = objectMapper.writeValueAsString(user);
                set(USER_PREFIX+user.getJti(),json);
                expireTime(USER_PREFIX+user.getJti(),SESSION_TIME);
            }
        }
        return user;
    }

    @Override
    public void clearUser(SecurityUser user) throws JsonProcessingException {
        del(USER_PREFIX+user.getJti());
    }
}
